package cl.ceis.demo1;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

public class LienzoGL extends GLSurfaceView {
	
	private LienzoRenderer renderer;
	private final float TOUCH_SCALE_FACTOR = 180.0f / 320;

	public LienzoGL(Context context, AttributeSet attrs) {
		super(context, attrs);	

	}

	public LienzoGL(Context context) {
		super(context);
		renderer = new LienzoRenderer();
		setRenderer(renderer);	
		setRenderMode(RENDERMODE_WHEN_DIRTY);
	}

	@Override
	public boolean onTouchEvent(final MotionEvent event) {
		
		float x = event.getX();
        float y = event.getY();
        
        float dx = x;
        float dy = y;
        
        
		
		Log.i("coordenada", dx  + ", " + dy);
		
		 queueEvent(new Runnable(){
	            public void run() {
	                renderer.setColor(event.getX() / getWidth(),
	                        event.getY() / getHeight(), 1.0f, event.getX(), event.getY());
	            }});		

		requestRender();
		return true;
	}
	
	

}

class LienzoRenderer implements GLSurfaceView.Renderer{

	private float mRed;
	private float mGreen;
	private float mBlue;
	private float winx;
	private float winy;
	private float winz;
	

	public void onDrawFrame(GL10 gl) {
		gl.glClearColor(mRed, mGreen, mBlue, 1.0f);
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		
		puntos((GL11) gl);
        

	}

	private void puntos(GL11 gl) {
		int[] viewport = new int[4];
        float[] modelview = new float[16];
        float[] projection = new float[16];
        float[] newcoords = new float[4];
		
        gl.glGetIntegerv(GL11.GL_VIEWPORT, viewport, 0);
        ((GL11) gl).glGetFloatv(GL11.GL_MODELVIEW_MATRIX, modelview, 0);
        ((GL11) gl).glGetFloatv(GL11.GL_PROJECTION_MATRIX, projection, 0);
        
        GLU.gluUnProject(winx, winy, winz, modelview, 0, projection, 0,   viewport, 0, newcoords, 0);
        float x = newcoords[0] / newcoords[3];
        float y = newcoords[1] / newcoords[3];
        float z = newcoords[2] / newcoords[3];
        
        Log.i("corr", "x: " + x + " y: " + y + " z: " + z );
	}

	public void setColor(float r, float g, float b, float x, float y) {
		mRed = r;
        mGreen = g;
        mBlue = b;
        
        winx = x;
        winy = y;
        winz = 0;
		
	}

	public void onSurfaceChanged(GL10 gl, int width, int height) {
		gl.glViewport(0, 0, width, height);
		
	}

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		
		
	}
	
}
